import com.mind.jenkins.pipeline.utils.BuildConfig

def call() {
    // properties([
            // parameters([
                    // string(defaultValue: '', description: '', name: 'COMMIT', trim: false),
                    // string(defaultValue: 'pre-release', description: '', name: 'BRANCH', trim: false),
                    // choice(choices: ['EVOFLOW-PRE', 'EVOFLOW-PROD', 'EVOFLOW-DEV'], description: '选择发布环境,默认pre', name: 'ENV'),
                    // choice(choices: ['pre-release', 'release'], description: '选择分支,默认pre-release', name: 'BRANCH'),
            // ])
    // ])

    dockerNode.golangBuildDocker {
        BuildConfig buildConfig
        boolean isSuccess = false
        def causes = currentBuild.getBuildCauses()
        def buildUser = causes[0]?.userId ?: 'Unknown'
        echo "Build User: ${buildUser}"
        try {
            if ("${ENV}" == "EVOFLOW-PROD"){
                stage('部署生产之前二次确认') {
                    input(message: "确定发布环境 ${ENV} 的 ${BRANCH}分支？", ok: 'Continue')
                }
            }
            stage('准备拉取代码') {
                //checkout scm
                checkout([
                        $class           : 'GitSCM',
                        branches         : [[name: BRANCH]],
                        userRemoteConfigs: scm.userRemoteConfigs
                ])
            }

            

            echo "当前发布环境：${ENV}, 当前发布分支：${BRANCH} "

            String appname = jobUtil.getAppNameFromJob()
            echo "当前服务名：${appname}"

            Object commitInfo = jobUtil.getCommitInfo()

            String imageAddr = jobUtil.getImageAdd(ENV)

            String imageName
            String coskey
            String nodejsVersion

            if (params.nodejsVersion == null){
                nodejsVersion = "nodejs-v14"
            }else{
                nodejsVersion = params.nodejsVersion
            }



            // stage('安装npm依赖') {
            //     nodejs(nodejsVersion){

            //         sh 'npm config set registry http://10.0.5.33:6532/;'
            //         if (appname == "mind-people-admin"){
            //             sh 'npm install --legacy-peer-deps'
            //         }else{
            //             sh 'npm install'
            //         }
                    
            //         if(appname == "mind-data"){
            //             sh 'npm run build -- --env.CI=false'
            //         }else if (appname == "mind-links"){
            //             sh 'npm run generate'
            //         }else if (appname == "mind-doc-for-shimo"){
            //             sh 'npm run build'
            //             sh 'npm run build:classic'
            //             sh 'cp -r _dist/* dist/'
            //             sh 'mv dist build'
            //         }else if (appname == "mind-doc-common-web"){
            //             sh 'npm ci --no-optional;'
            //             sh 'npm run build'
            //         }else{
            //             if(params.ENV == "EVOFLOW-PRE"){
            //                 sh 'npm run build:pre -- --env.CI=false'
            //             }else if (params.ENV == "EVOFLOW-PROD"){
            //                 sh 'npm run build:prod -- --env.CI=false'
            //             }else{
            //                 sh 'npm run build -- --env.CI=false'
            //             }
            //           }
            //     }

            // }


            stage('构建镜像') {        
                parallel 'docker': {
                    echo "Build docker image..."
                    imageName = "${imageAddr}/${appname}:${commitInfo.version}_${env.BUILD_NUMBER}"
                    dockerfile = "./deploy/Dockerfile"
                    jobUtil.buildDockerImage(dockerfile, "", "nodejs", imageName,"")
                }, 'cos': {
                     echo "构建文件上传COS中..."
                }
            }

            stage('单元测试') {
                echo "单元测试中...."
            }

            stage('质量检测') {
                echo "SonarScanner质量检查扫描中...."
            }

            stage('应用部署') {
                echo "Build success, Now Callback Cd..."
                String env = params.ENV
                if ( appname == "mind-job-server" ){
                    jobUtil.createBananaBuild(appname, "sts", env, buildUser, coskey, imageName, commitInfo, params.BRANCH)
                }else if (appname == "mind-sync-server" ){
                    jobUtil.createBananaBuild(appname, "cron", env, buildUser, coskey, imageName, commitInfo, params.BRANCH)
                }else{
                    jobUtil.createBananaBuild(appname, "deploy", env, buildUser, coskey, imageName, commitInfo, params.BRANCH)
                }
                
            }
        } finally {
            try {
                stage('通知') {
                    echo "通知工作群..."
                    isSuccess = currentBuild.result == null || currentBuild.result == 'SUCCESS'
                    String branch = params.BRANCH
                    String env = params.ENV
                    notifyUtil.notifyApp(jobUtil.getRepoName(), branch, env, isSuccess, buildUser)
                    String buildType = params.buildType
                    if (buildType != null && (buildType == "all" || buildType == "onlyPublish")){
                        switch(env) {
                            case "EVOFLOW-PRE":
                                sh "curl -X POST https://premind.im30.net/api/versionManage/webUpgrade"
                            break
                            case "EVOFLOW-PROD":
                            sh "curl -X POST https://mind.im30.net/api/versionManage/webUpgrade"
                            break
                        }
                    }

                }
                
            } catch (err) {
                echo err.getMessage()
            }
            // deleteDir()
        }
    }
}